<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ include file="/public/header.jsp"%>
<%
    String callback = request.getParameter("callback");
	String isShow = request.getParameter("isShow") == null ? "" : request.getParameter("isShow");
	String xm_id = request.getParameter("xm_id") == null ? "" : request.getParameter("xm_id");
	String dept_id = request.getParameter("dept_id") == null ? "" : request.getParameter("dept_id");
	String dept = request.getParameter("dept_name") == null ? "" : request.getParameter("dept_name");
	String xm_code = request.getParameter("xm_code") == null ? "" : request.getParameter("xm_code");
	String xm_name = request.getParameter("xm_name") == null ? "" : request.getParameter("xm_name");
	String customer_id = request.getParameter("customer_id") == null ? "" : request.getParameter("customer_id");
	String customer = request.getParameter("customer") == null ? "" : request.getParameter("customer");
	String id = request.getParameter("id") == null ? "" : request.getParameter("id");
	Map<String, Object> sessionMap = (Map<String, Object>) session.getAttribute("LOGIN_USER");
	String person_id = String.valueOf(sessionMap.get("id"));
	String person = String.valueOf(sessionMap.get("truename"));
	boolean isAdd = "".equals(id);
    int flag = 0;
    if(!isAdd){
    	flag = 1;
    }
%>
<html>
	<head>
		<title><%=isAdd?"新建项目毛利分摊":"编辑项目毛利分摊" %></title>
		<script type="text/javascript" src="<%=contextPath %>/public/js/extend.js"></script>
		<style>
			.td1{
				padding-top:10px;
				padding-bottom:5px;
				font-size: 12px;
				background-color: #c0ebd7;
				width:20%;
			}
			.td2{
				padding:5px;
			}
		</style>
	<script type="text/javascript">
		var lastIndex;
		$(function(){;
			var url="";
			$('#mtb').hide();
			if('<%=flag%>' == 1){
				jQuery('#ff').form({
				onLoadSuccess:function(){
				     jQuery('#person').val(jQuery('#creator').val());
				}
			});
		    jQuery('#ff').form('load','<%=contextPath%>/springMVC/xm/getXmvaluationById?id=<%=id%>');
		    url=contextPath+"/springMVC/xm/listXmvaluationDetail?fin_eval_id=<%=request.getParameter("id")%>";
			}else{
				jQuery("#operation_time").datebox('setValue',getTodaySecond());
			}
			
			 $('#table').datagrid({
		         	url:url,
					rownumbers:true,
					fitColumns:true,
					frozenColumns:[[
						{field:'ck',checkbox:true},
					    {title:'部门id',field:'dept_id',hidden:true}
					]],
					columns:[[
						{title:'部门名称',field:'dept_name',width:250,align:'center',editor:{
							type:'combotree',
							options:{
								url: '<%=contextPath %>/springMVC/group/listDepartment',
								method:'POST',
								animate:true,
								lines:true,
								onClick:function(rowData){
									if(checkSameDept(rowData.id,$('#table').datagrid('getData').rows)){
										var pRow = $('#table').datagrid('getRows')[lastIndex];
										pRow.dept_id = rowData.id;
										pRow.dept_name = rowData.text;
										$('#table').datagrid('getData').rows[lastIndex]=pRow;
										var data = $('#table').datagrid('getData');
										$('#table').datagrid('loadData',data);
										
										$('#table').datagrid('endEdit', lastIndex);
										$('#table').datagrid('beginEdit', lastIndex);
										//lastIndex =-1;
									}else{
										$.messager.alert("提示","选择的部门已经存在");
										$('#table').datagrid('acceptChanges');
										lastIndex =-1;
										var rows = $('#table').datagrid('getSelections');
										if (rows.length > 0){
											for(var i=0;i<rows.length;i++){
												var row = rows[i];
												var index = $('#table').datagrid('getRowIndex', row);
												$('#table').datagrid('deleteRow', index);
											}
										}
										var data = $('#table').datagrid('getData');
										$('#table').datagrid('loadData',data);
									}
								}
							}
						}},
						{title:'分摊利润(元)',field:'avg_profit',width:200,align:'center',
							editor:{
								type:'numberbox',
								options:{
									 min:0,    
		    						 precision:2 
								}
						}},
						{title:'备注',field:'remark',width:200,align:'center',editor:{
							type:'textarea'
						}}
					]],
					onBeforeLoad:function(){
						$(this).datagrid('rejectChanges');
					},
					   onAfterEdit:function(rowIndex, rowData, changes){
							shareProfit();
						},
						onLoadSuccess:function(rtJson){
							shareProfit();
						},
					onClickCell:function(rowIndex,field,value){
						if (lastIndex != rowIndex){
							$('#table').datagrid('endEdit', lastIndex);
							$('#table').datagrid('beginEdit', rowIndex);
							var ed = $('#table').datagrid('getEditor', {index:rowIndex,field:field});
							if(ed == null){
								ed = $('#table').datagrid('getEditor', {index:rowIndex,field:'out_invoice'});
							}
							$(ed.target).select();
						}
						lastIndex = rowIndex;
					},
					toolbar:[
						{
							id:'add',
							text:'选择部门',
							disabled:false,
							iconCls:'icon-add',
							handler:function(){
								var xm_id=jQuery("#xm_id").val();
								if(xm_id==''){
									jQuery.messager.alert("提示","请先选择项目,再进行毛利分摊！");
									return ;
								}
								addRow();
							}
						},'-',{
						id:'save',
						text:'保存修改',
						disabled:false,
						iconCls:'icon-save',
						handler:function(){
							$('#table').datagrid('acceptChanges');
							lastIndex =-1;
						}
						},'-',{
						id:'delete',
						text:'删除',
						disabled:false,
						iconCls:'icon-remove',
						handler:function(){
							shareProfit();
							$('#table').datagrid('acceptChanges');
							lastIndex =-1;
							var rows = $('#table').datagrid('getSelections');
							if (rows.length > 0){
								for(var i=0;i<rows.length;i++){
									var row = rows[i];
									var index = $('#table').datagrid('getRowIndex', row);
									$('#table').datagrid('deleteRow', index);
								}
							}
							var data = $('#table').datagrid('getData');
							$('#table').datagrid('loadData',data);
						}
					}
				   ]
				});
				
			});
			
			function checkSameDept(rowData,rows){
				if (rows.length > 0){
					for(var i=0;i<rows.length;i++){
						if(rows[i].dept_id==rowData){
							return false;
						}
					}
				}
				return true;
			}
			function addRow(){
				$('#table').datagrid('endEdit', lastIndex);
				$('#table').datagrid('appendRow',{
				});
				var data = $('#table').datagrid('getData');
				$('#table').datagrid('loadData',data);
				lastIndex = $('#table').datagrid('getRows').length-1;
				$('#table').datagrid('selectRow', lastIndex);
				$('#table').datagrid('beginEdit', lastIndex);
			}
		function addXMInvoiceRequest(obj){
			//自动提交数据
			$('#table').datagrid('acceptChanges');
			lastIndex =-1;
			//自动提交数据
			var xm_id =jQuery("#xm_id").val();	
			var xm_name=jQuery("#xm_name").val();	
			var xm_code=jQuery("#xm_code").val();
			var remark=encodeURIComponent(jQuery('#remark').val());
			if(!checkNullOREmpty(xm_id,'项目为必填项')){return;}
			var dept_id =jQuery("#dept_id").val();	
			var dept_name =jQuery("#dept_name").val();	
			var operation_time=jQuery("#operation_time").datebox('getValue');
			var evlaArr="";
			var jsondata=$("#table").datagrid("getData");
			var profit=0;
			var sum_profit=jQuery("#profit").val();
			for(var i=0;i<jsondata.total;i++){
				if(evlaArr!=""){
					evlaArr+=";";
				}
				evlaArr+=jsonToStr(jsondata.rows[i]);
				var index = $("#table").datagrid("getRowIndex",jsondata.rows[i])+1;
				if(jsondata.rows[i].dept_name == null || jsondata.rows[i].dept_name == ""){
					$.messager.alert('提示','第'+index+'行未选择部门！');
					return ;
				}else if(jsondata.rows[i].avg_profit == null || jsondata.rows[i].avg_profit == "" || jsondata.rows[i].avg_profit <= 0){
					$.messager.alert('提示','第'+index+'行分摊利润填写不正确！');
					return ;
				}
			}
		    var my_dept_profit=jQuery("#my_dept_profit").numberbox('getValue');
			var already_profit=jQuery("#already_profit").numberbox('getValue');
			if(parseFloat(already_profit)<=0){
		    	$.messager.alert('提示','利润分摊总额不能小于0，请重新输入！');
				return ;
		    }
		    if(parseFloat(profit)>parseFloat(sum_profit)){
		    	$.messager.alert('提示','利润分摊不正确,分摊金额应该不大于利润总额！');
				return ;
		    }
			var param = "remark="+remark+"&my_dept_profit="+my_dept_profit
			+"&operation_time="+operation_time
			+"&xm_id="+xm_id+"&xm_code="+xm_code+"&xm_name="+xm_name+"&dept_id="+dept_id+"&dept_name="+dept_name+"&evlaArr="+evlaArr+"&profit="+sum_profit+"&already_profit="+already_profit+"&creator_id=<%=person_id%>&creator=<%=person%>";
			$(obj).hide();
			$.ajax({
				type:'POST',
				<%=isAdd?"url:'"+contextPath+"/springMVC/xm/addXmEvaluation',":"url:'"+contextPath+"/springMVC/xm/updateXmEvaluation?id="+id+"',"%>
				data:param,
				dataType:'json',
				success:function(rtJson){
					if(rtJson.rtState == '0'){
						eval('window.opener.<%=callback%>();');
						window.close();
					}
					else{
						$.messager.alert("提示",rtJson.rtMsrg);
					}
					$(obj).show();
				}
			});
		}
		function choseXm(){
		    	openDialogResize("<%=contextPath %>/springViews/xm/choseMyXM.jsp",1000, 800);
		    	
		}
		function rtCallBackXmSet(xm_id,xm_code,xm_name,deptId,dept){
			jQuery("#xm_id").val(xm_id);
		    jQuery("#xm_name").val(xm_name);
		    jQuery("#xm_code").val(xm_code);
		    jQuery("#dept_name").val(dept);
		    jQuery("#dept_id").val(deptId);
		    sumProfit(xm_id);
		}
		function sumProfit(xm_id){
			var param="xm_id="+xm_id;
			var sumProfit=0;
			jQuery.ajax({
					type:'GET',
					url:'<%=contextPath %>/springMVC/xm/getXmEvalById',
					dataType:"JSON",
					async:false,
					data:param,
					success:function(rowData){
						//已经收款金额+已经还款金额-借款报销金额-管理费-本次税金-直接报销金额-扣款金额-采购金额-进度项目支付金额-进度扣款金额-垫款金额-结算项目结算金额-结算扣款金额-已经分摊金额
							sumProfit=parseFloat((rowData.has_receivable+rowData.already_money)-(rowData.loan_reimburs+rowData.xm_manage_price+rowData.company_tax+rowData.direct_reimburse+rowData.work_cut_pay+rowData.purchase_has_payable+rowData.pay_value+rowData.advancesMoney+rowData.work_end_pay)-(rowData.already_profit)).toFixed(2);
							 jQuery("#profit").numberbox('setValue', sumProfit);
					}
				});
			
		}
		function shareProfit(){
			var already_profit = 0;
			var my_dept_profit = 0;
			var jsondata=$("#table").datagrid("getData");
			var dept_id= jQuery("#dept_id").val();
			for(var i=0;i<jsondata.total;i++){
				var row = jsondata.rows[i];
				if(row.avg_profit == null  || row.avg_profit == '' ){
					continue;
				}
				already_profit += parseFloat(row.avg_profit);
				if(row.dept_id==dept_id){
					my_dept_profit = parseFloat(row.avg_profit);
				}
			}
			$('#already_profit').numberbox("setValue",already_profit);
			$('#my_dept_profit').numberbox("setValue",my_dept_profit);
		}
	</script>
	</head>
	<body>
		<div style="width: 97%;padding-left:10px">
		<form id="ff">
		<input type="hidden" id="creator" name="creator"/>
			<table  style="border-collapse: collapse;" width="100%" border="1px" bordercolor="#0eb83a">
				<tr>
					<td align="right" class="td1" nowrap>项目编号：</td>
					<td class="td2" nowrap>
						<input  id="xm_code" name="xm_code" readOnly value="<%=xm_code%>">
						<input type="hidden" id="xm_id" name="xm_id" readOnly value="<%=xm_id%>">
						<%if(!"1".equals(flag)){ %>
						<a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-add',plain:false" onclick="choseXm();"></a>								</td>
						<%} %>
					</td>
					<td align="right" class="td1" nowrap>项目名称：</td>
					<td class="td2" nowrap>
						<input  id="xm_name" name="xm_name" readOnly value="<%=xm_name%>">
					</td>
				</tr>
				<tr>
					<td align="right" class="td1" nowrap>项目部门：</td>
					<td class="td2" nowrap>
						<input  id="dept_name" name="dept_name" readOnly value="<%=dept%>">
						<input  type="hidden" id="dept_id" name="dept_id" readOnly value="<%=dept_id%>">
					</td>
					<td align="right" class="td1" nowrap>经办人：</td>
					<td class="td2" nowrap>
						<input  id="person" name="person" readOnly value="<%=person%>">
					</td>
				</tr>
				<tr>	
				    <td align="right" class="td1" nowrap>日期：</td>
					<td class="td2" nowrap >
						<input  id="operation_time" name="operation_time" class="easyui-datebox" data-options="required:true"/>
					</td>		
			        <td align="right" class="td1" nowrap>项目利润：</td>
					<td class="td2" nowrap>
						<input  id="profit" name="profit"   class="easyui-numberbox" readonly="readonly" data-options="precision:2,required:true" >
					</td>
				<tr>
				<tr>	
				    <td align="right" class="td1" nowrap>本部门利润：</td>
					<td class="td2" nowrap >
						<input  id="my_dept_profit" name="my_dept_profit"   class="easyui-numberbox" readonly="readonly" data-options="precision:2,required:true"  >
					</td>		
			        <td align="right" class="td1" nowrap>分摊利润总额：</td>
					<td class="td2" nowrap>
						<input  id="already_profit" name="already_profit"   class="easyui-numberbox" readonly="readonly" data-options="precision:2,required:true" >
					</td>
				<tr>
				<tr>
					<td align="right" class="td1" nowrap>摘要：</td>
					<td class="td2" nowrap colspan='3'>
						<textarea  id="remark" name="remark" rows="6" style="width: 100%"></textarea>
					</td>
				</tr>
				<%if(!"1".equals(isShow)){ %>
				<tr>
					<td align="right" class="td1" nowrap></td>
					<td class="td2" nowrap colspan='3'>
						<div align="left">
						   
							<a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-save',plain:false" onclick="addXMInvoiceRequest(this);">提交</a>
							
							<a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-cancel',plain:false" onclick="javascript:window.close();">关闭</a>
						</div>
					</td>
				</tr>
				<%} %>
				<tr>
					<td colspan="4"  nowrap>
						<div id="myMsg" style="color:red">项目利润分摊到相关部门</div>
					</td>
				</tr>			
				<tr>
					<td colspan="4"  nowrap>
						<div id="table"></div>
					</td>
				</tr>
			</table>
			</form>
		</div>
		
	</body>
</html>